import React from 'react';
import { Editor } from '@tiptap/react';
import axios from 'axios';
import dayjs from 'dayjs';
import { useNavigate } from 'react-router-dom';
interface HistoryItem {
  _id: number;
  project_id: number;
  content: string;
  created_at: string;
}

interface HistorySidebarProps {
  editor: Editor;
  provider: any;
  lists: HistoryItem[];
  setIsEditMode: (value: boolean) => void;
  setCurrentEditId: (value: number | null) => void;
  defaultContent: string;
  currentEditId: number | null;  // 添加当前编辑ID属性
}

const HistorySidebar: React.FC<HistorySidebarProps> = ({
  editor,
  provider,
  lists,
  setIsEditMode,
  setCurrentEditId,
  defaultContent,
  currentEditId,
}) => {
  const decodeContent = (content: string) => {
    try {
      // 使用浏览器原生的 base64 解码方式
      const decoded = new TextDecoder().decode(
        Uint8Array.from(atob(content), c => c.charCodeAt(0))
      );
      const parsedContent = JSON.parse(decoded);
      return parsedContent.content || parsedContent;
    } catch (error) {
      // 如果解码失败，尝试直接解析
      try {
        const parsedContent = JSON.parse(content);
        return parsedContent.content || parsedContent;
      } catch {
        console.error('内容解码失败:', error);
        return null;
      }
    }
  };
  const navigate = useNavigate();
  const handleHistoryItemClick = (content: string, projectId: number) => {
    if (!editor) return;

    const contentObj = decodeContent(content);
    if (!contentObj) {
      console.error('无法加载历史内容');
      return;
    }

    editor.commands.clearContent();
    setTimeout(() => {
      editor.commands.setContent({
        type: 'doc',
        content: contentObj
      });
    }, 100);

    setIsEditMode(true);
    setCurrentEditId(projectId);

    provider.awareness.setLocalStateField('editMode', {
      isEditMode: true,
      currentEditId: projectId
    });
  };



  const handleNew = () => {
    editor.commands.setContent(defaultContent);
    setIsEditMode(false);
    setCurrentEditId(null);

    provider.awareness.setLocalStateField('editMode', {
      isEditMode: false,
      currentEditId: null
    });
  };

  const xinxi = () => {
    navigate('/yao');

  }

  const renwu = () => {
    navigate('/cywindex');

  }
  return (
    <div className="history-sidebar">
      <div className="history-header">
        <div className="history-tab active">历史</div>
        <div className="history-tab" onClick={handleNew}>新建</div>
        <div className="history-tab" onClick={xinxi}>信息</div>
        <div className="history-tab" onClick={renwu}>任务</div>
      </div>
      <div className="history-content">
        {lists.map((item, index) => {
          const contentObj = decodeContent(item.content);
          if (!contentObj) return null;

          const isActive = currentEditId === item._id;

          // 提取预览文本
          const previewText = Array.isArray(contentObj)
            ? contentObj
              .filter(node => node.type === 'paragraph')
              .map(node => node.content?.[0]?.text || '')
              .join(' ')
            : '';

          return (
            <div
              className={`history-item ${isActive ? 'active' : ''}`}
              key={item._id || index}
              onClick={() => handleHistoryItemClick(item.content, item._id)}
            >
              <div className="history-item-header">
                <span className="history-item-title">
                  墨客-{item.project_id} 编辑了文档
                </span>
                <span className="history-item-time">
                  {dayjs(item.created_at).format('MM月DD日 HH:mm')}
                </span>
              </div>
              <div className="history-item-preview">
                {previewText.substring(0, 50)}...
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

export default HistorySidebar;